package com.andnnl.fileanalysis;

import cn.hutool.core.util.StrUtil;
import com.opencsv.CSVReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;

/**
 * csv文件读取
 * Created by chenss on 2021/6/2.
 */
public class CsvAnalysis extends AbsFileAnalysis {
    private static final Logger logger = LoggerFactory.getLogger(CsvAnalysis.class);

    public CsvAnalysis() {

    }

    /**
     * 去除 字符串收尾的 特殊的Unicode [ "\uFEFF" ]
     * csv 文件可能会带有该编码
     *
     * @param str
     * @return
     */
    public static String specialUnicode(String str) {
        if (str.startsWith("\uFEFF")) {
            str = str.replace("\uFEFF", "");
        } else if (str.endsWith("\uFEFF")) {
            str = str.replace("\uFEFF", "");
        }
        return str;
    }

    @Override
    public void analysis(InputStream is, AnalysisListenerBase listener, AnalysisParam param) {
        try (CSVReader reader = new CSVReader(new InputStreamReader(is, param.getCharset()))) {
            String[] strArr = null;
            int rowCount = 0;
            int rowNum = 0;//行号，从1开始,初始为0
            boolean isFirst = true;
            while ((strArr = reader.readNext()) != null && (param.getMaxRow() == 0 || rowCount < param.getMaxRow())) {
                rowNum++;//累计
                if(strArr.length==0) continue;
                if (isFirst) {
                    isFirst = false;
                    strArr[0] = StrUtil.trim(strArr[0]);//UTF-8+BOM编码时，会用UTF-8编码读取，前面会有空格，这里去掉
                }
                if (param.getDelHeadRows() > param.getHeadRowCount()) {
                    param.getHeadRowCountAndAdd();
                    logger.info("ignore head:" + Arrays.toString(strArr));
                    handleHead(Arrays.asList(strArr),rowNum, listener, param);
                    continue;
                }
                rowCount++;
                handleRow(Arrays.asList(strArr),rowNum, listener, param);//处理第一行
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            super.finish(listener, param);//文件读取完成
            listener.finish();//监听完成
        }
    }
}
